//
//  Request.swift
//  ClockWidget
//
//  Created by TSYH on 2023/8/8.
//

import Alamofire
import ObjectMapper

open class BaseRequest {
    public var method: String
    public var params: Parameters? = nil
    public var responseClass: Mappable.Type
    public var mockFile: String?
    public var localFile: String?
    public var shouldCacheResponse: Bool = false
    public var shouldReadCache: Bool = false
    
    public init(method: String, 
                params: Parameters? = nil,
                responseClass: Mappable.Type,
                mockFile: String? = nil, localFile: String? = nil,
                shouldCacheResponse: Bool = false,
                shouldReadCache: Bool = false) {
        self.method = method
        self.params = params
        self.responseClass = responseClass
        self.mockFile = mockFile
        self.localFile = localFile
        self.shouldCacheResponse = shouldCacheResponse
        self.shouldReadCache = shouldReadCache
    }
    
    open func model(from data: Data) throws -> Any {
        do {
            let object = try JSONSerialization.jsonObject(with: data)
            if let dict = object as? [String: Any],
                let model = responseClass.init(JSON: dict) {
                return model
            } else {
                throw RequestSession.RequestError.businessError(code: 4100, message: "JSON Format exception")
            }
        } catch let error {
            throw error
        }
    }
}

public enum CacheType {
    case none           // 无缓存
    case memory         // 内存缓存
    case disk           // 沙盒缓存
}

extension BaseRequest {
    // 请求对应的缓存key
    var dataCacheKey: String {
        var result = method
        if let params = params, !params.isEmpty {
            result.append("?")
            params.keys.sorted().forEach { key in
                result.append("\(key)=\(params[key] ?? "")")
            }
        }
        return result.md5String ?? result
    }
}
